/**
 * 0. Project	: com.dnbns.lib 프로젝트
 *
 * 1. FileName	: AlarmDB.java
 * 2. Package	: com.dnbns.lib
 * 3. 작성자		: 윤화현
 * 4. 작성일		: 2013. 12. 31. 오전 9:51:35
 * 5. Comment	: 
 */

package com.dnbns.lib;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class AlarmDB extends SQLiteOpenHelper {
	
	public static final String DATABASE_NAME = "ALARM.db";
	public static final int DATABASE_VERSION = 4;

	/** Water Data */
	public static final String TABLE_ALARM	 		= "ALARM";
	public static final String KEY_WATER_IDX		= "idx";
	public static final String KEY_WATER_HOUR		= "hour";
	public static final String KEY_WATER_MINUTE		= "minute";
	
    public AlarmDB(Context context) {
        // Database이름은 실제 단말상에서 생성될 파일이름입니다. data/data/package명/databases/DATABASE_NAME식으로 저장
		super(context, DATABASE_NAME, null, DATABASE_VERSION);	
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub         
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
    }

	public synchronized JSONArray execute(String query) {
		SQLiteDatabase db = getReadableDatabase();
		String sql = query;
		Cursor cursor = db.rawQuery(sql, null);
		JSONArray objA = new JSONArray();

		try {
			int columnCount = cursor.getColumnCount();
			while(cursor.moveToNext()){
				JSONObject obj = new JSONObject();
				for(int i=0; i<columnCount; i++){
					String name = null;
					String value = null;
					try{
						name = cursor.getColumnName(i);
						value = cursor.getString(i);
					}catch(NullPointerException e){
						e.printStackTrace();
						Log.i("TEST", "Exception query : " + query);
					}
					if(name != null){
						if(value == null){
							value = "";
						}
						obj.put(name, value);
					}
				}
				objA.put(obj);
			}	
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			cursor.close();
			db.close();
		}
		
		return objA;
	}
}
